package com.yuntsg.ruiijn.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.ruiijn.databse_search.entity.FileDetailsTxt;
import com.yuntsg.ruiijn.databse_search.entity.FileRecord;
import com.yuntsg.ruiijn.databse_search.service.FileRecordsService;
import com.yuntsg.ruiijn.paperana.service.MatchService;
import common.bean.RRException;
import common.util.CheckUtil;
import common.util.MinioUtil;
import common.util.StringUtil;
import common.vo.Scenario;
import io.minio.GetObjectResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: gcr
 * @Date: 2023/10/10 8:45
 */
@Slf4j
@Service
public class ManualCheckService {
    //整合代码到一起 与wos 表关联


    @Value("${upload.path}")
    public String uploadPath;

    @Value("${upload.resultPath}")
    public String resultPath;

    @Resource
    MinioUtil minioUtil;

    @Resource
    UserUtil userUtil;

    @Resource
    MatchService matchService;


    @Resource
    FileRecordsService fileRecordsService;

    public static String getdoiTimeYear(String doi) {
        String res = "";
        if (StringUtil.isNotNull(doi)) {
            String s = HttpUtil.get("https://pm.yuntsg.com/utils/getarticleYear?type=1&q=" + URLEncoder.encode(doi));
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject.get("code").toString().equals("0")) {
                Object data = jsonObject.get("data");
                res = data.toString();
            }

        }
        return res;
    }

    public static String getpmutmatch(String pmid) {
        String res = "";
        if (StringUtil.isNotNull(pmid)) {
            String s = HttpUtil.get("https://pm.yuntsg.com/utils/getpmutmatch?q=" + URLEncoder.encode(pmid));
            if (StringUtils.isNotBlank(s)) {
                return s.replace("WOS:", "");
            }
        }
        return res;
    }

    /**
     * 获取pm 或者ut 年份
     *
     * @param pmut
     * @param type
     * @return
     */
    public static Integer getpmutYear(String pmut, Integer type) {
        log.info("getpmutYear+pmut+" + pmut + "+type+" + type);
        Integer year = null;
        if (StringUtil.isNull(pmut) || StringUtil.isNull(type)) {
            return year;
        }
        try {
            String s = HttpUtil.get("https://pm.yuntsg.com/utils/getpmutyear?type=" + type + "&q=" + URLEncoder.encode(pmut));
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject.get("code").toString().equals("0")) {
                Object data = jsonObject.get("data");
                if (StringUtil.isNotNull(data.toString())) {
                    year = Integer.parseInt(data.toString());
                }
            }
        } catch (Exception e) {

        }
        return year;
    }

    public static void main(String[] args) {
        Integer i = getpmutYear("10.5812/ijradiol-128065", 2);
        System.out.println(i);

    }

    public static MultipartFile getMultipartFile(File file) {
        MultipartFile cMultiFile = null;
        try {
            cMultiFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));

        } catch (Exception e) {

        }
        return cMultiFile;
    }

    public String getut(String pmid) {
        String res = "";
        if (StringUtil.isNotNull(pmid)) {
            String s = HttpUtil.get("https://pm.yuntsg.com/utils/getpmut?type=1&q=" + URLEncoder.encode(pmid));
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject.get("code").toString().equals("0")) {
                Object data = jsonObject.get("data");
                res = data.toString();
            }

        }
        return res;
    }

    @SneakyThrows
    /**
     * 单文档对比上传
     */
    public Integer dealSinCheck(Integer type, String content, String author, String title, String filePath, String pmut, Integer uid) {

        MultipartFile file = null;
        if (StringUtil.isNotNull(filePath)) {
            log.info("路径+" + uploadPath + filePath);
            String filePah = uploadPath + filePath;
            file = getMultipartFile(new File(filePah));
        }
        //0 文本  2 文档
        String md5 = null;
        Integer backReid = 0;
        if (type == 0) {
            String tempName = uploadPath + RandomUtil.randomString(5) + ".txt";
            log.info("粘贴文本写入的文件路径+" + tempName);
            File temp = new File(tempName);
            FileUtil.writeUtf8String(content, temp);
            boolean exist = FileUtil.exist(temp);
            log.info("temp文件存在吗?+" + exist);
            md5 = SecureUtil.md5(temp);
            log.info("粘贴文本md5" + md5);
            String path = minioUtil.upload(FileUtil.getInputStream(temp), uid, DateUtil.today(), temp.getName(), Scenario.txt);
            log.info("path++" + path);
            FileRecord fileRecord = new FileRecord().setType(type).setAuthor(author).setTitle(title).setFilePath(path).setUploadId(uid).setUploadTime(DateUtil.date().getTime()).setMd5(md5);
            fileRecordsService.saveOrUpdate(fileRecord);
            GetObjectResponse getObjectResponse = minioUtil.downloadIm(path);
            System.out.println("getObjectResponse+" + getObjectResponse);
            fileRecordsService.extractFilesText(getObjectResponse, fileRecord.getId(), uid, 0, tempName, 1);
            backReid = fileRecord.getId();

            // 异步不能删除 还没处理完就删除了后面走不了 后期处理
//            try {
//                FileUtil.del(temp);
//            } catch (Exception e) {
////                e.printStackTrace();
//            }
        } else if (type == 2) {

            CheckUtil.check(StringUtil.isNotNull(file), "文件丢失");
            String path = minioUtil.upload(file.getInputStream(), uid, DateUtil.today(), file.getOriginalFilename(), Scenario.documentation);
            FileRecord fileRecord = new FileRecord().setType(type).setAuthor(author).setPmut(pmut).setTitle(title).setFilePath(path).setUploadId(uid).setUploadTime(DateUtil.date().getTime()).setMd5(md5);
            fileRecordsService.saveOrUpdate(fileRecord);
            fileRecordsService.extractFilesText(file.getInputStream(), fileRecord.getId(), uid, file.getOriginalFilename().toLowerCase().endsWith("pdf") ? 2 : 1, "", 1);
            backReid = fileRecord.getId();
        }


        return backReid;
    }

    public Integer dealSinCheckAsync(Integer type, String content, String author, String title, String filePath, String pmut, Integer uid) {
        MultipartFile file = null;
        String md5 = null;
        Integer backReid = 0;
        String tempName = uploadPath + RandomUtil.randomString(5) + ".txt";
        FileUtil.writeString(content, tempName, StandardCharsets.UTF_8);
        File temp = new File(tempName);
        md5 = SecureUtil.md5(temp);
        String path = minioUtil.upload(FileUtil.getInputStream(temp), uid, DateUtil.today(), temp.getName(), Scenario.txt);
        FileRecord fileRecord = new FileRecord().setType(type).setAuthor(author).setTitle(title).setFilePath(path).setUploadId(uid).setUploadTime(DateUtil.date().getTime()).setMd5(md5);
        fileRecordsService.saveOrUpdate(fileRecord);
        fileRecordsService.extractFilesText(minioUtil.downloadIm(path), fileRecord.getId(), uid, 0, tempName, 1);
        backReid = fileRecord.getId();
        try {
            FileUtil.del(temp);
        } catch (Exception e) {
//                e.printStackTrace();
        }
        return backReid;
    }

    @SneakyThrows
    /**
     *  多文档对比上传
     */
    /**
     *
     * @param type
     * @param content
     * @param author
     * @param title
     * @param file1
     * @param file2
     * @param pmut
     * @return
     */
    public Integer dealMulCheck(String filePath1, String filePath2, String author, String title) {

        CheckUtil.check(StringUtils.isNotEmpty(filePath1), "文件1 路径丢失");
        CheckUtil.check(StringUtils.isNotEmpty(filePath2), "文件2 路径丢失");
        MultipartFile file1 = getMultipartFile(new File(uploadPath + filePath1));
        MultipartFile file2 = getMultipartFile(new File(uploadPath + filePath2));

        // file1 默认原始文档 file2 待比对文档
        if (null == file1 || file2 == null) {
            throw new RRException("文件都必须提交！！");
        }
        String path = minioUtil.upload(file1.getInputStream(), userUtil.getUid(), DateUtil.today(), file1.getOriginalFilename(), Scenario.documentation);
        String md5 = SecureUtil.md5(file1.getInputStream());
        //默认拿第一个
        MultipartFile fileParamNew = file1;
        FileRecord fileRecord = new FileRecord().setType(3).setAuthor(author).setPmut("").setTitle(title).setFilePath(path).setUploadId(userUtil.getUid()).setUploadTime(DateUtil.date().getTime()).setMd5(md5);
        fileRecordsService.saveOrUpdate(fileRecord);
        fileRecordsService.extractFilesText(fileParamNew.getInputStream(), fileRecord.getId(), userUtil.getUid(), fileParamNew.getOriginalFilename().toLowerCase().endsWith("pdf") ? 2 : 1, "", 2);
        //待比对的文件进行自定义es库
        List<FileDetailsTxt> pdf = fileRecordsService.extractFilesBackStr(file2.getInputStream(), fileRecord.getId(), userUtil.getUid(), file2.getOriginalFilename().toLowerCase().endsWith("pdf") ? 2 : 1, "");
        boolean b = matchService.dealManualData(pdf, fileRecord.getId(), userUtil.getUid());
        if (!b) {
            throw new RRException("文件入库异常");
        }

        return fileRecord.getId();

    }


}
